<template>
  <view class="warp">
	 <view class="flex_row_between_center" style="padding-top: 120rpx;">
		  <view class="filter"></view>
		  <view class="filter3 flex_row_center_center">
			  <image src="../../static/images/other/log2.png" mode="aspectFit" class="logo_image"></image>
		  </view>
		  <view class="filter2"></view>
	  </view>
	  <view>
		 <view  class="login_list" >
			  <view class="login_list_label">手机号</view>
			  <view style="">
				  <input placeholder="请输入手机号" :value="mobile" @input="inputChange" @blur="handleAcc" 
				   maxlength="20" data-key="mobile" class="input-item" placeholder-class="placeholder-class" />
			  </view>
		  </view>
		  <view  class="login_list" >
			  <view class="login_list_label">密码</view>
			  <view style="">
				  <input placeholder="请输入密码" :value="password" @input="inputChange" 
						:adjust-position="false" 
				    maxlength="20" :password="!showPwd" data-key="password" class="input-item" placeholder-class="placeholder-class" />
			  </view>
		  </view>
		  <view class="login_button flex_row_center_center" :style="{ opacity: !(mobile && password) || logining ? 0.5 : 1 }" @click="toLogin">立即登录</view>
	  </view>
	  <view class="register_button" @click="getRegister">注册</view>
	  <!-- #ifdef APP -->
			  <view class="flex_row_between_center" style="margin: 0  40px;">
				<button  class="wechat-login2"  @click="getPhone">
						  <image  :src="url" mode="aspectFill" />
					<text>本机一键登录</text>
				</button>
				<button  class="wechat-login2"  @click="quickLogin">
					 <image  src="https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/yijing/%E5%BE%AE%E4%BF%A1.png" mode="aspectFill" />
				   <text>微信</text>
				</button>
			  </view>
	  <!-- #endif -->
	 
	  <!-- #ifdef MP-WEIXIN -->
	  <button class="wechat-login2" @tap="getUserProfile">
	  	<image  src="https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/yijing/%E5%BE%AE%E4%BF%A1.png"  mode="aspectFill" />
	  	<text>一键登录</text>
	  </button>
	    
	  <!-- #endif -->
	  <!-- #ifdef MP-WEIXIN -->
	  <wxBindPhone ref="wxBindPhone"></wxBindPhone>
	  <!-- #endif -->
     
     
  </view>
</template>

<script>
import wxBindPhone from '@/components/wxBindPhone.vue'
import {mapMutations,mapState} from 'vuex'
  export default {
	components: {wxBindPhone},
    data() {
      return {
		  mobile: '',
		  password: '',
		  showPwd: false,
		  logining:false,
		  wxClient: 1,
          url:'https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/yijing/phone_icon.png'
      }
    },
	onLoad(){
		this.client = this.$getLoginClient()
		this.wxClient = this.$wxLoginClient()
	},
    methods: {
	 ...mapMutations(['login', 'setUserCenterData']),
	  toLogin(){
		  if (!(this.mobile && this.password) ) {
		  	uni.showToast({
		  		title: '请输入账号密码',
		  		icon: 'none',
		  		duration: 700
		  	})
		  	return
		  }
		  
		  this.logining = true
		  const {
		  	mobile,
		  	password
		  } = this
		  //密码的验证 6～20位，英文、数字或符号
		  if (!this.$checkPwd(password)) {
		  	this.logining = false
		  	return false
		  }
		  let param = {}
		  param.url = 'v3/frontLogin/oauth/token'
		  param.data = {}
		  param.data.username = mobile //登陆类型为1时：是用户名；为2时：是手机号
		  param.data.password = this.$base64Encrypt(password)
		  param.data.loginType = 1 //登陆类型：1-账号密码登陆，2-手机验证码登陆
		  param.data.source = this.$getLoginClient()
		  // #ifdef APP-PLUS
		  param.data.clientId = uni.getStorageSync('clientId');
		  // #endif
		  param.method = 'POST'
		  this.$request(param).then((res) => {
			  // console.log('res',res);
			  if (res.state == 200) {
				  //更新登录时间
				  uni.setStorage({
				  	key: 'sld_login_time',
				  	data: new Date().getTime()
				  })
				  this.login(res.data)
				  //获取个人中心的数据
				  this.$request({
				  		url: 'v3/member/front/member/memberInfo'
				  	}).then((result) => {
				  		this.setUserCenterData(result.data)
						uni.navigateBack()
						// if(result.data.loginNumber>1){
						// 	uni.navigateTo({
						// 		url:'/pages/index/profileLead/profileLead'
						// 	})
						// }else{
						// 	uni.navigateBack()
						// }
				  	})
			  }else {
				//错误提示
				this.$modal.msg(res.msg)
			}
			this.logining = false
		  })
	  },
	  inputChange(e) {
		// console.log('e',e);
	  	const key = e.currentTarget.dataset.key
	  	this[key] = e.detail.value
		// console.log(this[key]);
	  },
	  handleAcc() {
	  	let regEn = /[`~!@#$%^&*()+<>?:"{},.\/;'[\]]/gi,
	  		regCn = /[·！#￥（——）：；“”‘，|《。》？【】[\]]/gi
	  	if (regEn.test(this.mobile) || regCn.test(this.mobile)) {
	  		this.mobile = ''
	  		this.$api.msg(this.$L('名称不能包含特殊字符.'))
	  	}
	  },
	  //是否显示密码切换事件
	  changePwdState() {
	  	this.showPwd = !this.showPwd
	  },
	 
      getUserProfile(e) {
      	// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
      	// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      	uni.getUserProfile({
      		desc: "用于完善个人信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      		success: (res) => {
				console.log('res',res);
      			if (res.errMsg == 'getUserProfile:ok') {
      				let userinfo = res.userInfo
      				this.getWxXcxCoce(userinfo)
      			}
      		},
      		
      	})
      },
	  //微信小程序根据用户信息获取code
	  getWxXcxCoce(userinfo) {
	  	let {
	  		client
	  	} = this
	  	let _this = this
	  	uni.showLoading({
	  		title: '正在请求...',
	  		mask: true
	  	})
	  	uni.login({
	  		success: (code) => {
				console.log('code',code);
	  			let tar_params = {}
	  			tar_params.source = _this.wxClient
	  			tar_params.code = code.code
	  			tar_params.userInfo = JSON.stringify(userinfo)
	  			_this.goLogin(tar_params)
	  		}
	  	})
	  },
	  // 授权登录
	  quickLogin() {
		  let {
		  	client
		  } = this
		  let _this = this
		  // if (!this.check_agreement) {
		  // 	this.$api.msg(this.$L('请同意用户隐私政策!'))
		  // 	return false
		  // }
		  // let networkType = ''
		  // uni.getNetworkType({
		  // 	success: (res) => {
		  // 		if (res.networkType == 'none') {
		  // 			networkType = res.networkType
		  // 			setTimeout(() => {
		  // 				uni.hideLoading();
		  // 				uni.removeStorageSync('netNetworkFlag')
		  // 				uni.navigateTo({
		  // 					url: '/standard/netNetwork/netNetwork'
		  // 				})
		  // 			})
		  // 		}
		  // 	},
		  // })
		  // if (networkType == 'none') {
		  // 	return false
		  // }
		  
		  
		  uni.login({
		  	provider: 'weixin',
		  	success: function(loginRes) {
		  		if (loginRes.errMsg == 'login:ok') {
		  			//授权登录成功
		  			// 获取用户信息
		  			uni.getUserInfo({
		  				provider: 'weixin',
		  				success: function(infoRes) {
							console.log('infoRes',infoRes);
		  					let tar_params = {}
		  					tar_params.unionid = loginRes.authResult.unionid
		  					tar_params.openid = loginRes.authResult.openid
		  					tar_params.userInfo = JSON.stringify(infoRes.userInfo)
		  					tar_params.source = _this.wxClient
		  					_this.goLogin(tar_params)
		  				}
		  			})
		  		}
		  	},
		  	complete(info) {
		  		console.log(info, "info")
		  	}
		  })
	  },
	  goLogin(data) {
	  	let _this = this
	  	let param = {}
	  	param.url = 'v3/member/front/login/wechat/login'
	  	param.data = {
	  		...data
	  	}
	  	param.method = 'POST'
		
		// #ifdef APP-PLUS
		param.data.clientId = uni.getStorageSync('clientId');
		// #endif
		console.log('param',param);
	  	this.$request(param).then((res) => {
			 console.log('res-goLogin',res);
	  		uni.hideLoading()
	  		if (res.state == 200) {
	            console.log('res.data.redirect',res.data.redirect);
				if (res.data.redirect == undefined) {
					_this.login(res.data)
					_this.$request({
							url: 'v3/member/front/member/memberInfo'
						}).then((result) => {
							console.log('result',result);
							_this.setUserCenterData(result.data)
						})
						_this.$tab.navigateBack()
						 
				}else if(res.data.redirect != undefined){
					console.log('222222222');
					//用户未注册，需要绑定手机号进行注册
					// #ifndef MP-WEIXIN
					console.log('res.data.bindKey',res.data.bindKey);
					let url='/pages/public/bindMobile'
					let params=res.data.bindKey
					uni.navigateTo({
					   url: `${url}?params=${params}`
					});
					
					// #endif
					
					// #ifdef MP-WEIXIN
						this.$refs.wxBindPhone.openKey(res.data.bindKey)
					// #endif
				}else{
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					})
				}
	  			
	  		}else{
					_this.$modal.msg(res.msg)
			} 
	  	})
	  },
	  getNumLogin(){
		  uni.login({
		  	provider: 'univerify',
		  	univerifyStyle: {
		      fullScreen: true
		    }
		  })

	  },
	  getRegister(){
		  this.$tab.navigateTo('/pages/public/register')
	  },
	  /* 本机一键登录*/
	 getPhone(){
	 	//在这里写一键登录的代码
		let _this=this
	 	uni.preLogin({
	 		provider: 'univerify',
	 		success(){  //预登录成功
	 			// 显示一键登录选项
	 			uni.login({
	 				provider: 'univerify',
	 				univerifyStyle: { 
	 				// 自定义登录框样式
	 			    //参考`univerifyStyle 数据结构`
	 				//具体样式设计请去uni-app文档查看
	 				//不填写任何自定义登录框样式的话就会采取默认样式
	 			  },
	 				success(res){ // 登录成功
	 					console.log(res.authResult.access_token);
	 					console.log(res.authResult.openid);
	 					// 此处获取了openid和access_token
	 					// {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
	 					// 通过uniCloud.callFunction函数实现前端获取手机号
	 					uniCloud.callFunction({
	 				      name: "testLogin", // 填写你自己的云函数名称
	 					  //传入上面获取的openid和access_token获取手机号
	 				      data: {
	 				        access_token: res.authResult.access_token, // 客户端一键登录接口返回的access_token
	 				        openid: res.authResult.openid // 客户端一键登录接口返回的openid
	 				      }
	 				    })
	 				    .then((dataRes) => {
	 					  //此处已经成功获取手机号等信息
	 				      console.log("云函数返回的参数", dataRes)
	 				      let phone = dataRes.result.data.phoneNumber
	 				      // 获取手机号后根据自己的需求做后面的登录操作即可
						  console.log("云函数返回的phone", phone)
						    _this.toPhone(phone)
	 					  //...
	 				    })
	 				    .catch((err) => {
	 						console.log(err);
	 				      console.log("云函数报错", err)
	 				      uni.showToast({
	 				        title: err.errMsg,
	 				        icon: "none"
	 				      })
	 				     
	 				      setTimeout(() => {
	 				        uni.closeAuthView() //关闭一键登录弹出窗口
	 				        _this.onClickMsgLogin()
	 				      }, 500)
	 				    })
	 				},
	 				fail(res){  // 登录失败
	 					console.log(res.errCode)
	 					console.log(res.errMsg)
	 				}
	 			})
	 		},
	 		fail(res){  
	 		// 预登录失败
	 		// 不显示一键登录选项（或置灰）
	 	    // 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
	 			console.log(res.errCode)
	 			console.log(res.errMsg)
	 		}
	 	})
	 },
	 toPhone(mobile){
		 //
		 let param = {}
		 param.url = 'v3/frontLogin/oauth/token'
		 param.data = { }
		 param.data.username=mobile
		 param.data.loginType = 3
		 param.method = 'POST'
		 
		 console.log('param',param);
		 this.$request(param).then((result) => {
			 // console.log('result',result);
			  if (result.state == 200) {
				  console.log('成功！');
				  this.login(result.data)
				  //获取个人中心的数据
				  this.$request({
				  		url: 'v3/member/front/member/memberInfo'
				  	}).then((result1) => {
						 console.log('result1',result1);
						uni.closeAuthView() //关闭一键登录弹出窗口
				  		this.setUserCenterData(result1.data)
				  		uni.navigateBack()
				  	})
			  }else {
					//错误提示
					this.$modal.msg(res.msg)
				}
		 })
	 },
      
    }
  }
</script>
<style>
	page{
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	/* 本机一键登录 */
	.warp{
		// background-color: #d9eefa;
	}
	.register_button{
		text-align: right;
		padding-right: 12%;
		color:#3cd0ec;
	}
    .wechat-login2{
		margin-top: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		background: transparent;
		line-height: auto;
		height: auto;

		&::after {
			border: none;
		}

		image {
			width: 70rpx;
			height: 70rpx;
		}

		text {
			color: #666666;
			font-size: 24rpx;
		}
	}
  .login_list{
	  margin:46rpx  64rpx 0 64rpx ;
	  color: #1E2121;
	  font-size: 32rpx;
	
	  .login_list_label{
	  	  margin-bottom: 22rpx;
	  	  color: #1E2121;
	  	  
	  }
	  .input-item{
	  	  font-size: 28rpx;
	  	  height: 16rpx;
	  	  padding-bottom: 16rpx;
	  	  border-bottom: 2rpx solid #EDF0F0;
	  }
  }
  .wechat-login {
	margin-top: 40rpx;
  	display: flex;
  	flex-direction: column;
  	align-items: center;
  	width: 60%;
	padding: 10rpx 0;
	border-radius: 40rpx;
  	// background: transparent;
  	background: #9E4035;
  	line-height: auto;
  	height: auto;
  
  	&::after {
  		border: none;
  	}
  
  	image {
  		width: 78rpx;
  		height: 78rpx;
  	}
  
  	text {
  		// color: #666666;
		color: #fff;
  		font-size: 26rpx;
  	}
  }
  .login_button{
	  margin:62rpx 64rpx 48rpx 64rpx;
	  background-color: #3cd0ec;
	  color: #fff;
	  font-size: 32rpx;
	  height: 88rpx;
	  border-radius: 48rpx;
  }
  .filter {
	   width: 254rpx;
	   height: 370rpx;
	   // background: #dec4b4;
	   background-color: #d9eefa;
	   filter: blur(260rpx);
  }
  .filter2{
	   width: 250rpx;
	    height: 380rpx;
	    // background:#dec4b4;
		background-color: #d9eefa;
	    filter: blur(280rpx);
		// background-image: linear-gradient(to bottom left, red , yellow);
  }
  .filter3{
	   flex: 1;
	   height: 380rpx;
	   
	  // background:#edd6c066;;
	  background: radial-gradient(circle, #fff 0%,transparent 100%);
	  // filter: opacity(0.1);
  }
  .logo_image{
	 
	  width: 264rpx;
	  height: 264rpx;
	  z-index: 999;
  }

 

</style>
